package com.itboye.ihomebank.activity.electric_meter;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.github.mikephil.charting.charts.Chart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.MPPointF;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.FeeDailyBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.datepicker.wheelview.OnWheelScrollListener;
import com.itboye.ihomebank.custom.datepicker.wheelview.WheelView;
import com.itboye.ihomebank.custom.datepicker.wheelview.adapter.ArrayWheelAdapter;
import com.itboye.ihomebank.custom.datepicker.wheelview.adapter.NumericWheelAdapter;
import com.itboye.ihomebank.presenter.ElectricMeterPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Observable;

public class ActivityElecTariffTrend extends BaseOtherActivity {


    View v_statusbar;
    ImageView close_icon;
    TextView add_shap_title_tv;

    private LineChart lineChart;
    private XAxis xAxis;                //X轴
    private YAxis leftYAxis;            //左侧Y轴
    private YAxis rightYAxis;           //右侧Y轴 自定义XY轴值
    private Legend legend;              //图例
    private LimitLine limitLine;        //限制线
//  private MyMarkerView markerView;    //标记视图 即点击xy轴交点时弹出展示信息的View 需自定义

    private ElectricMeterPresenter presenter;
    private String uid;
    private String aid;//小区或房间 id
    private String start;
    private String end;

    //linechart数据
    private List<FeeDailyBean> dailyBeans;
    private boolean isFirst=true;

    private String titleDate;//markview title date(2018.12)

    private ImageView select_time;

    private TextView priEle,pubEle;
    private TextView lineName;

    @Override
    protected int layout_id() {
        return R.layout.activity_electariff;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {

        //初始化曲线
//        initChart(lineChart);
//        LineChartBean lineChartBean = LocalJsonAnalyzeUtil.JsonToObject(this,
//                "chart.json", LineChartBean.class);
//        List<IncomeBean> list = lineChartBean.getGRID0().getResult().getClientAccumulativeRate();
//        showLineChart(list, "我的收益", Color.CYAN);

//        //设置背景
//        lineChart.setBackgroundColor(getResources().getColor(R.color.white));
//        //是否显示边界
//        lineChart.setDrawBorders(false);
//        //是否展示网格线
//        lineChart.setDrawGridBackground(false);
//
//        //其实那是 X Y轴自己的网格线，禁掉即可
//        xAxis.setDrawGridLines(false);
//        rightYaxis.setDrawGridLines(false);
//        leftYAxis.setDrawGridLines(true);
//        // 设置X Y轴网格线为虚线（实体线长度、间隔距离、偏移量：通常使用 0）
//        leftYAxis.enableGridDashedLine(10f, 10f, 0f);
//        //目标效果图没有右侧Y轴，所以去掉右侧Y轴
//        rightYaxis.setEnabled(false);

//        // X轴值的定义 在 showLineChart 方法中我们会传入X轴的值，所以自定义X轴的值可以 写在该方法内
//        xAxis.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
////                String tradeDate = dataList.get((int) value % dataList.size()).getTradeDate();
////                return DateUtil.formatDate(tradeDate);
//                return "";
//            }
//        });
        //设置X轴分割数量
//        xAxis.setLabelCount(6,false);

//        //Y轴值的自定义
//        leftYAxis.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//                return ((int) (value * 100)) + "%";
//            }
//        });
//        leftYAxis.setLabelCount(8);

        //调用修改
//        showLineChart(list, "我的收益", getResources().getColor(R.color.blue));
//        Drawable drawable = getResources().getDrawable(R.drawable.fade_blue);
//        setChartFillDrawable(drawable);

        //发现图表的右下角还有一个描述标签 Descripition Lable 需要在LineChart初始化时设置一下
//        Description description = new Description();
//        description.setText("需要展示的内容");
//        description.setEnabled(false);
//        lineChart.setDescription(description);

        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("电费走势");
        //初始化数据
        initLineData();


        //然后调用改方法即可，也可以在 showLineChart方法中 创建两条曲线。
//        showLineChart(list, "我的收益", getResources().getColor(R.color.blue));

//        List<CompositeIndexBean> indexBeanList = lineChartBean.getGRID0().getResult().getCompositeIndexShanghai();
//        addLine(indexBeanList, "上证指数", getResources().getColor(R.color.orange));



    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.close_icon:
                 this.finish();
                break;
            case R.id.select_time:
                showSelectPop();
                break;
        }
    }

    //初始化 presenter 和请求当前月份的数据
    private void initLineData() {

        dailyBeans=new ArrayList<>();
        uid= SPUtils.get(this,null, SPContants.USER_ID,"")+"";
        aid = getIntent().getStringExtra("aid");
        presenter=new ElectricMeterPresenter(this);
        //默认当前月份的曲线
        Calendar instance = Calendar.getInstance();
        int year = instance.get(Calendar.YEAR);
        int mon = instance.get(Calendar.MONTH)+1;
        SimpleDateFormat format = new SimpleDateFormat("MM");

        titleDate=year+"."+mon;
        lineName.setText(year+"年"+mon+"月电费走势");
        int linchartWidth = getDaysOfMonth(new Date(System.currentTimeMillis()));

        start=year+""+format.format(new Date(System.currentTimeMillis()))+"01";
        end=year+""+format.format(new Date(System.currentTimeMillis()))+""+linchartWidth;
        showProgressDialog("数据请求中...",false);
        presenter.feeDaily(uid,aid,start,end,"");

    }

    //获取月份的天数
    private int getDaysOfMonth(Date date) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }




    @Override
    protected void onReadIntent(Bundle bundle) {

    }



    /**
     * 初始化图表
     */
    private void initChart(LineChart lineChart) {
        /***图表设置***/
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        lineChart.setBackgroundColor(Color.WHITE);
        //是否显示边界
        lineChart.setDrawBorders(false);
        //是否可以拖动
        lineChart.setDragEnabled(true);
        lineChart.setDoubleTapToZoomEnabled(false);

        //是否有触摸事件
        lineChart.setTouchEnabled(true);

        //设置XY轴动画效果
//        lineChart.animateY(500);
//        lineChart.animateX(500);
        Description description = new Description();
//        description.setText("需要展示的内容");
        description.setEnabled(false);
        lineChart.setDescription(description);


        /***XY轴的设置***/
        xAxis = lineChart.getXAxis();
        leftYAxis = lineChart.getAxisLeft();
        rightYAxis = lineChart.getAxisRight();

        xAxis.setDrawGridLines(false);
        rightYAxis.setDrawGridLines(false);
        leftYAxis.setDrawGridLines(true);
        //设置Y轴网格线为虚线
        leftYAxis.enableGridDashedLine(10f, 10f, 0f);
        rightYAxis.setEnabled(false);

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
        rightYAxis.setAxisMinimum(0f);

        /***折线图例 标签 设置***/
        legend = lineChart.getLegend();
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(12f);
        //显示位置 左下方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
        //是否显示
        legend.setEnabled(false);
    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     * @param color       线条颜色
     * @param mode
     */
    private void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(3f);
        lineDataSet.setDrawCircles(false);
        lineDataSet.setDrawValues(false);
//        //设置曲线值的圆点是实心还是空心
//        lineDataSet.setDrawCircleHole(false);
//        lineDataSet.setValueTextSize(10f);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15.f);
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
//        if (mode == null) {
//            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
//            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
//        } else {
//            lineDataSet.setMode(mode);
//        }
    }


    public class LineBean {
        /**
         * rate : -0.00034196
         * tradeDate : 20180502
         */
        private float rate;
        private String tradeDate;


        public LineBean(float rate, String tradeDate) {
            this.rate = rate;
            this.tradeDate = tradeDate;
        }

        public float getRate() {
            return rate;
        }

        public void setRate(float rate) {
            this.rate = rate;
        }

        public String getTradeDate() {
            return tradeDate;
        }

        public void setTradeDate(String tradeDate) {
            this.tradeDate = tradeDate;
        }
    }

    /**
     * 展示曲线
     *
     * @param dataList 数据集合
     * @param name     曲线名称
     * @param color    曲线颜色
     */
    public void showLineChart(List<LineBean> dataList, String name, int color) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            LineBean data = dataList.get(i);
            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */
            Entry entry = new Entry(i,data.getRate());
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        lineDataSet.setDrawValues(false);
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        LineData lineData = new LineData(lineDataSet);
        lineChart.setData(lineData);
    }




    /**
     * 设置线条填充背景颜色
     *
     * @param drawable
     */
    public void setChartFillDrawable(Drawable drawable) {
        if (lineChart.getData() != null && lineChart.getData().getDataSetCount() > 0) {
            LineDataSet lineDataSet = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
            //避免在 initLineDataSet()方法中 设置了 lineDataSet.setDrawFilled(false); 而无法实现效果
            lineDataSet.setDrawFilled(true);
            lineDataSet.setFillDrawable(drawable);
            lineChart.invalidate();
        }
    }



    public class LineChartMarkView extends MarkerView {

        private TextView title;

        private String xAxisValueFormatter;
        private List<FeeDailyBean> dailys;
        private LinearLayout rootLl;
        DecimalFormat df = new DecimalFormat("0.00");

        public LineChartMarkView(Context context, String xAxisValueFormatter,List<FeeDailyBean> dailys) {
            super(context, R.layout.layout_markview);
            this.xAxisValueFormatter = xAxisValueFormatter;
            this.dailys=dailys;
            title = (TextView) findViewById(R.id.title);
            rootLl= (LinearLayout) findViewById(R.id.rootLl);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void refreshContent(Entry e, Highlight highlight) {
            Chart chart = getChartView();
            int  positon= (int) e.getX();
            Log.d("===position",positon+"");
            if (chart instanceof LineChart) {
                    //遍历所有曲线
                    for (int i=0;i<dailys.size();i++){
                        TextView textView;
                        if (rootLl.getChildAt(i+1)==null){
                            textView = new TextView(ActivityElecTariffTrend.this);
                            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            params.leftMargin=60;
                            params.rightMargin=60;
                            params.topMargin=10;
                            params.bottomMargin=10;
                            params.gravity=Gravity.CENTER_HORIZONTAL;
                            textView.setLayoutParams(params);
                            textView.setTextSize(12);
                            rootLl.addView(textView);
                        }else {
                            textView= (TextView) rootLl.getChildAt(i+1);
                        }

                        FeeDailyBean.Data dataSet = dailys.get(i).getData().get(positon);

//                        BigDecimal thisvalue = new BigDecimal(dailys.get(i).getData().get((int) e.getX()).getThis_value().trim());
//                        BigDecimal lastvalue = new BigDecimal(dailys.get(i).getData().get((int) e.getX()).getLast_value().trim());
                        Log.d("====smart",dailys.get(i).getData().get((int) e.getX()).getThis_value()+"==="
                                +dailys.get(i).getData().get(positon).getLast_value());
                        Log.d("====type",dailys.get(i).getMeter_type().trim()+"position=="+positon);
//                        lin.add(new LineBean(thisvalue.subtract(lastvalue).floatValue(),""));
                        if (dailys.get(i).getMeter_type().trim().equals("2")){ //私有
                            if (dailys.get(i).getData().get((int) e.getX()).getFee()==null||"".equals(dailys.get(i).getData().get((int) e.getX()).getFee().trim())){
                                textView.setText("私用电-"+dailys.get(i).getName()+" : "+0+"元   "+dataSet.getLast_value()+"-"+dataSet.getThis_value());
                            }else {
                                textView.setText("私用电-"+dailys.get(i).getName()+" : "+(float)Integer.parseInt(dailys.get(i).getData().get((int) e.getX()).getFee())/100+"元   "+dataSet.getLast_value()+"-"+dataSet.getThis_value());

                            }

                        }else  if (dailys.get(i).getFee()==null||dailys.get(i).getMeter_type().trim().equals("1")){ //公有
                            if (dailys.get(i).getData().get((int) e.getX()).getFee()==null||"".equals(dailys.get(i).getData().get((int) e.getX()).getFee().trim())){
                                textView.setText("公用电"+" : "+0+"元   "+dataSet.getLast_value()+"-"+dataSet.getThis_value());
                            }else {
                                textView.setText("公用电"+" : "+(float)Integer.parseInt(dailys.get(i).getData().get((int) e.getX()).getFee())/100+"元   "+dataSet.getLast_value()+"-"+dataSet.getThis_value());
                            }

                        }else { //未分配
//                            textView.setText("未知电"+i+":"+thisvalue.subtract(lastvalue).floatValue()+"   "+dataSet.getLast_value()+"-"+dataSet.getThis_value());
                        }
                    }
                    title.setText(xAxisValueFormatter+"."+((int) e.getX()+1));


            }
            super.refreshContent(e, highlight);
        }

        @Override
        public MPPointF getOffset() {
            return new MPPointF(-(getWidth() / 2), -getHeight());
        }
    }

    /**
     * 设置 可以显示X Y 轴自定义值的 MarkerView
     */
    public void setMarkerView(List<FeeDailyBean> dailys) {
        LineChartMarkView mv = new LineChartMarkView(this,titleDate,dailys);
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);
        lineChart.invalidate();
    }



    /**
     * 添加曲线
     */
    private void addLine(List<LineBean> dataList, String name, int color) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            LineBean data = dataList.get(i);
            Entry entry = new Entry(i, data.getRate());
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        lineDataSet.setDrawValues(false);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        lineChart.getLineData().addDataSet(lineDataSet);
        Drawable drawable = getResources().getDrawable(R.drawable.fade_green);
        setChartFillDrawable(drawable);
        lineChart.invalidate();
    }



    public void resetLine(int position, List<LineBean> dataList, String name, int color) {
        LineData lineData = lineChart.getData();
        List<ILineDataSet> list = lineData.getDataSets();
        if (list.size() <= position) {
            return;
        }

        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            LineBean data = dataList.get(i);
            Entry entry = new Entry(i, (float) data.getRate());
            entries.add(entry);
        }

        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);

        lineData.getDataSets().set(position, lineDataSet);
        lineChart.invalidate();
    }

    float pris,pubs;
    @Override
    public void update(Observable observable, Object data) {
        super.update(observable, data);
        ResultEntity entity = handlerError(data);
        if (entity!=null){

            try{
                closeProgressDialog();
            }catch (Exception e){

            }
            if (entity.getEventType()==ElectricMeterPresenter.BY_Emeter_feeDaily_success){
                if (dailyBeans.size()>0){
                    dailyBeans.clear();
                    pris=0;
                    pubs=0;
                }
                List<FeeDailyBean> data1 = (List<FeeDailyBean>) entity.getData();

                initChart(lineChart);

                for (int i=0;i<data1.size();i++){
                    if (i==0){
                        List<LineBean> lin=new ArrayList<>();
                        for (int j=0;j<data1.get(i).getData().size();j++){ //添加曲线数据
                            Log.d("===fee",Float.parseFloat(data1.get(i).getData().get(j).getFee())+"");
                            int fee=Integer.parseInt(data1.get(i).getData().get(j).getFee());
                            float fee_value=fee/100;
                            lin.add(new LineBean(fee_value,""));
                            BigDecimal socre1 = new BigDecimal(pris+"");
                            BigDecimal socre2 = new BigDecimal(pubs+"");
                            BigDecimal socre3 = new BigDecimal(fee_value+"");
                            if (data1.get(i).getMeter_type().trim().equals("2")){ //私有
                                pris = socre1.add(socre3).floatValue();
                            }else  if (data1.get(i).getMeter_type().trim().equals("1")){ //公有
                                pubs=socre2.add(socre3).floatValue();
                            }else { //未分配
                            }
                        }
                        if (data1.get(i).getMeter_type().trim().equals("2")){ //私有
                            showLineChart(lin, "私用电量"+i, getResources().getColor(R.color.blue));
                        }else  if (data1.get(i).getMeter_type().trim().equals("1")){ //公有
                            showLineChart(lin, "公用电量", getResources().getColor(R.color.tariffLine_green));
                        }else { //未分配
                            showLineChart(lin, "未知电量", getResources().getColor(R.color.tariffLine_green));
                        }

                    }else {
                        List<LineBean> lin=new ArrayList<>();
                        for (int j=0;j<data1.get(i).getData().size();j++){ //添加曲线数据
                            Log.d("===fee",Float.parseFloat(data1.get(i).getData().get(j).getFee())+"");
                            int fee=Integer.parseInt(data1.get(i).getData().get(j).getFee());
                            float fee_value=fee/100;
                            lin.add(new LineBean(fee_value,""));
                            BigDecimal socre1 = new BigDecimal(pris+"");
                            BigDecimal socre2 = new BigDecimal(pubs+"");
                            BigDecimal socre3 = new BigDecimal(fee_value+"");
                            if (data1.get(i).getMeter_type().trim().equals("2")){ //私有
                                pris = socre1.add(socre3).floatValue();
                            }else  if (data1.get(i).getMeter_type().trim().equals("1")){ //公有
                                pubs=socre2.add(socre3).floatValue();
                            }else { //未分配
                            }
                        }

                        if (data1.get(i).getMeter_type().trim().equals("2")){ //私有
                            addLine(lin, "私用电量", getResources().getColor(R.color.blue));
                        }else  if (data1.get(i).getMeter_type().trim().equals("1")){ //公有
                            addLine(lin, "公用电量", getResources().getColor(R.color.tariffLine_green));
                        }else { //未分配
                            addLine(lin, "未知电量", getResources().getColor(R.color.tariffLine_green));
                        }

                    }

                }
                Drawable drawable = getResources().getDrawable(R.drawable.fade_blue);
                setChartFillDrawable(drawable);
                setMarkerView(data1);


//                dailyBeans.addAll(data1);

//                for (int i=0;i<dailyBeans.size();i++){ //展示电费曲线  一条数据一条曲线
//
//
//                    pris+=Float.parseFloat(dailyBeans.get(i).getVal_pri());
//                    pubs+=Float.parseFloat(dailyBeans.get(i).getVal_pub());
////                    dailyBeans.get(i).setVal_pri((int)(Math.random()*30)+"");
////                    dailyBeans.get(i).setVal_pub((int)(Math.random()*30)+"");
//                }
                pubEle.setText("公用电费"+pubs);
                priEle.setText("私用电费"+pris);
                Log.d("====size",dailyBeans.size()+"");
                //刷新曲线表
//                List<LineBean> privateBeans=new ArrayList<>();
//                List<LineBean> publicBeans=new ArrayList<>();
//                for (FeeDailyBean bean:dailyBeans) {
//                    privateBeans.add(new LineBean(Float.parseFloat(bean.getVal_pri()),""));
//                    publicBeans.add(new LineBean(Float.parseFloat(bean.getVal_pub()),"") );
//                }


//                }else {
////                    showLineChart(privateBeans, "私用电量", getResources().getColor(R.color.blue));
//                    resetLine(0, privateBeans, "私用电量", getResources().getColor(R.color.blue));
//                    resetLine(1, publicBeans, "公用电量", getResources().getColor(R.color.tariffLine_green));
//                    setMarkerView(dailyBeans);
//                }
                isFirst=false;
            }else if (entity.getEventType()==ElectricMeterPresenter.BY_Emeter_feeDaily_fail){

                ByAlert.alert(entity.getMsg());
            }
        }
    }



    //日期选择弹框
    Calendar c;
    private WheelView year;
    private WheelView month;
    private WheelView day;
    private WheelView time;
    private WheelView min;
    private WheelView sec;

    PopupWindow datePop;
    private String yearSlect;
    private String monthSelect;
    //显示
    private void showSelectPop() {

        c = Calendar.getInstance();
        int norYear = c.get(Calendar.YEAR);
        int curDate = c.get(Calendar.DAY_OF_MONTH);
        int curMonth = c.get(Calendar.MONTH)+1;
        int curHour=c.get(Calendar.HOUR_OF_DAY);
        int curMin=c.get(Calendar.MINUTE);
        View view = LayoutInflater.from(this).inflate(
                R.layout.popup_choosetime, null);
        year = (WheelView) view.findViewById(R.id.year);

        NumericWheelAdapter numericWheelAdapter1 = new NumericWheelAdapter(
                this, norYear-4, norYear);
        numericWheelAdapter1.setLabel("年");
        yearSlect=norYear+"";
        year.setViewAdapter(numericWheelAdapter1);
        year.setCyclic(false);// �Ƿ��ѭ������
        year.addScrollingListener(scrollListener);

        month = (WheelView) view.findViewById(R.id.month);

        NumericWheelAdapter numericWheelAdapter2 = new NumericWheelAdapter(
                this, 1, 12, "%02d");
        numericWheelAdapter2.setLabel("月");
        month.setViewAdapter(numericWheelAdapter2);
        month.addScrollingListener(scrollListener);
        monthSelect=String.format("%02d", curMonth);
        month.setCurrentItem(curMonth-1);
        month.setCyclic(true);
        day = (WheelView) view.findViewById(R.id.day);
//        initDay(norYear, curMonth, this);
//        day.setCurrentItem(curDate);
//        day.setCyclic(true);
//
//        day.addScrollingListener(scrollListener);
        time = (WheelView) view.findViewById(R.id.time);
//        String[] times = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
//                "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
//                "21", "22", "23", "24" };
//        ArrayWheelAdapter<String> arrayWheelAdapter = new ArrayWheelAdapter<String>(
//                context, times);
//        time.setViewAdapter(arrayWheelAdapter);
//        time.setCyclic(true);
//        time.addScrollingListener(scrollListener);

        min = (WheelView) view.findViewById(R.id.min);
//        NumericWheelAdapter numericWheelAdapter3 = new NumericWheelAdapter(
//                context, 1, 59, "%02d");
//        numericWheelAdapter3.setLabel("分");
//        min.setViewAdapter(numericWheelAdapter3);
//        min.setCyclic(true);
//        min.addScrollingListener(scrollListener);

        sec = (WheelView) view.findViewById(R.id.sec);
//        NumericWheelAdapter numericWheelAdapter4 = new NumericWheelAdapter(
//                context, 1, 59, "%02d");
//        numericWheelAdapter4.setLabel("秒");
//        sec.setViewAdapter(numericWheelAdapter4);
//        sec.setCyclic(true);
//        sec.addScrollingListener(scrollListener);

        year.setVisibleItems(7);// ������ʾ����
        month.setVisibleItems(7);
//        day.setVisibleItems(7);
//        time.setVisibleItems(7);
//        min.setVisibleItems(7);
//        sec.setVisibleItems(7);

        day.setVisibility(View.GONE);
        time.setVisibility(View.GONE);
        min.setVisibility(View.GONE);
        sec.setVisibility(View.GONE);

        year.setCurrentItem(4);
		month.setCurrentItem(curMonth-1);
//        day.setCurrentItem(curDate - 1);
//        time.setCurrentItem(curHour-1);
//        min.setCurrentItem(curMin-1);
//        sec.setVisibility(View.GONE);

        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                datePop.dismiss();
            }
        });

        TextView ok = (TextView) view.findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //请求数据
                titleDate=yearSlect+"."+monthSelect;
                SimpleDateFormat format = new SimpleDateFormat("yyyy.MM");

                try {
                    int linchartWidth = getDaysOfMonth(format.parse(titleDate));
                    start=yearSlect+""+monthSelect+"01";
                    end=yearSlect+""+monthSelect+""+linchartWidth;
                    lineName.setText(yearSlect+"年"+monthSelect+"月电费走势");
                    showProgressDialog("数据请求中...",false);

                    presenter.feeDaily(uid,aid,start,end,"");
                    datePop.dismiss();
                    Log.d("======timeSel","start=="+start+"end=="+end);
                } catch (ParseException e) {
                    Log.d("===exca",e.getMessage());
                    e.printStackTrace();
                }

            }
        });
        datePop=new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
//        datePop.setAnimationStyle(R.style.popupwindow_anim_style);
//        datePop.setContentView(contentView);
//        ColorDrawable dw = new ColorDrawable(0xb000000);
//        datePop.setBackgroundDrawable(dw);
        //passwordpop 可点击
        view.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        view.setFocusableInTouchMode(true); //comment by danielinbiti,设置view能够接听事件 标注2
        datePop.showAtLocation(view, Gravity.BOTTOM,0,0);




    }

    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {
        @Override
        public void onScrollingStarted(WheelView wheel) {
            // if (isStart){
            //
            // }
        }
        @Override
        public void onScrollingFinished(WheelView wheel) {
            switch (wheel.getId()){
                case R.id.year:
                    int yearItem = wheel.getCurrentItem();
                    Calendar instance = Calendar.getInstance();
                    int currentYear = instance.get(Calendar.YEAR)-4+yearItem;
                    yearSlect=currentYear+"";
                    Log.d("=======ye",yearSlect);
                    break;
                case R.id.month:
                    int mothItem = wheel.getCurrentItem()+1;
                    monthSelect=String.format("%02d", mothItem);
                    Log.d("=======ye",monthSelect);
                    break;
            }
        }
    };

}
